<template>
    <view >
        <image v-if="type=='image'" @click="chooseImage()" :style="{width: iconInfo.width, height: iconInfo.width}" :src="iconInfo.icon" mode="aspectFill"></image>
        <image v-else-if="type=='video'" @click="chooseVideo()" :style="{width: iconInfo.width, height: iconInfo.width}" :src="iconInfo.icon" mode="aspectFill"></image>
        <!-- <lsj-upload 
             v-else-if="type=='video'"
            ref="lsjUpload2"
            childId="upload2"
            wxFileType="video"
            :width="iconInfo.width"
            :height="iconInfo.width"
            :option="uploadOption"
            :size="size"
            :debug="debug"
            :count="9"
            :instantly="instantly"
            @change="onChange"
            @progress="onprogress"
            @uploadEnd="onuploadEnd"
            >
                <image class="btn" :style="{width: iconInfo.width, height: iconInfo.width}" :src="iconInfo.icon" mode="aspectFill"></image>
            </lsj-upload> -->
        <lsj-upload 
            v-else-if="type=='file'"
            ref="lsjUpload"
            childId="upload1"
            wxFileType="file"
            :width="iconInfo.width"
            :height="iconInfo.height||iconInfo.width"
            :option="uploadOption"
            :size="size"
            :formats="formats"
            :debug="debug"
            :count="9"
            :instantly="instantly"
            @change="onChange"
            @progress="onprogress"
            @uploadEnd="onuploadEnd"
            >
                <image v-if="iconInfo.icon" class="btn" :style="{width: iconInfo.width, height: iconInfo.width}" :src="iconInfo.icon" mode="aspectFill"></image>
                <view class="upload-file" v-else>
					<image src="/static/campus/upload.png" mode="widthFix"></image>
					<text>上传文件</text>
				</view>
            </lsj-upload>
    </view>
</template>
<script>
import SparkMD5 from 'spark-md5'
import md5Str from '@/static/md5.min.js'
export default {
    data() {
        return{
            notConfirmImages: [],
            sendImages: [],
            confirmImages: [],

            // 上传接口参数
            uploadOption: {
                // 上传服务器地址，此地址需要替换为你的接口地址
                // url: 'https://xiaode-2f00.obs.cn-east-3.myhuaweicloud.com',
                url: '',
                // 上传附件的key
                name: 'file',
                formData: {}
            },
            // 选择文件后是否立即自动上传，true=选择后立即上传
            instantly: false,
            // 限制允许上传的格式，空串=不限制，默认为空
            formats: '',
            // 文件上传大小限制
            size: 150,
            // 是否打印日志
            debug: true,
            uploladFileNumber: 0,

            sendMsgType: 1, // 1是图片，8是文件
            selectAllFlies: []

        }
    },
    props: {
        iconInfo: {
            type: Object,
            default: ()=>{}
        },
        userType: {
            type: String,
            default: '1'
        },
        userId: {
            type: Number,
            default: 0
        },
        type: {
            type: String,
            default: ''
        },
    },
    methods: {
        onuploadEnd(item) {
            uni.hideLoading()
            let isAll = [...this.files.values()].find(item=>item.type!=='success');
            if (!isAll) {
                if(this.sendMsgType==8&&this.sendImages.length == this.uploladFileNumber){
                    this.confirmUploadFile(this.confirmImages)
                }else if(this.sendMsgType==3&&this.confirmImages.length == this.uploladFileNumber){
                    this.confirmUploadFile(this.confirmImages)
                }
            }
            else {
                // console.log(isAll.name+'待上传');
            }
            
        },
        // 上传进度回调
        onprogress(item) {
            // console.log('上传进度:',item)
            uni.showLoading({
                title: '上传中',
                mask: true
            });
            
        },
        // 文件选择回调
        onChange(files, list, concat) {
            this.$emit('selectFile', this.iconInfo.id)
            // 更新选择的文件
            this.files = files;
            this.sendMsgType = this.type=='video'?3:8
            
            list = list || []
            this.uploladFileNumber = concat
            
            // #ifdef APP-PLUS
            // list = [list]
            // concat = 1
            // this.uploladFileNumber = 1
            list = [...this.files.values()]
            // list = [JSON.parse(list)[0][1]]
            
            // #endif
            this.sendImages = [];
            this.confirmImages = []
            // return
            uni.setStorageSync('wweee', list)
            if(list.length == concat){
                this.chooseFileChange(list)
            }
            
            
            // 强制更新视图
            this.$forceUpdate();
        },
        uploadFile(path, info, len){
            let uploadUrl = `https://${info.uploadUrl}/`
            if(this.sendMsgType==8){
                this.uploadOption.url = uploadUrl;
                let formData = {
                    key: info.key,
                    AccessKeyId: info.accessKeyId, // 上线删除
                    Policy: info.policy,
                    Signature: info.signature
                }
                this.uploladFileNumber = len;
                if(this.sendMsgType==8){
                    this.$refs.lsjUpload.setData('url', uploadUrl)
                    this.$refs.lsjUpload.setData('formData', formData)
                    this.$refs.lsjUpload.upload();
                }else{
                    this.$refs.lsjUpload2.setData('url', uploadUrl)
                    this.$refs.lsjUpload2.setData('formData', formData)
                    this.$refs.lsjUpload2.upload();
                }
  
                return
            }
            let that = this
            
            uni.uploadFile({
                url: uploadUrl, 
                filePath: path,
                formData: {
                    key: info.key,
                    AccessKeyId: info.accessKeyId, 
                    Policy: info.policy,
                    Signature: info.signature
                },
                success: (uploadFileRes)=>{
                    if(uploadFileRes.data==''){
                        this.sendImages.push(info.key);
                    let num = this.notConfirmImages.length+this.sendImages.length
                    if(num == len){
                        that.confirmUploadFile(this.confirmImages)
                    }
                    }
                    
                    
                },fail:(err)=>{
                    console.log(212, err);
                }
            })
        },
        confirmUploadFile(info){
            let path = this.userId?'file/confirmUploadFile':'file/xiaodeConfirmUploadFile'
            this.api.post(path, {
                confirmFile: JSON.stringify(info)
            }).then(res=>{
                if(res.data.state != 'ok') return;
                let list = this.notConfirmImages.concat(this.sendImages)
                let sendFiles = []
                for(let i=0; i<list.length; i++){
                    let path = list[i];
                    if(this.sendMsgType==8){
                        path = list[i].path
                    }
                    sendFiles.push({type: path.split('.').pop(), path: path, msgType: this.sendMsgType, name: this.sendMsgType==8?list[i].name:'', size: list[i].size})
                }
                 this.$emit('chooseFile', this.sendMsgType, this.selectAllFlies, sendFiles)
                // this.sendMsg(this.sendMsgType, JSON.stringify(list))

            })
        },
        chooseFileChange(files){

            let type = '';
            let fileInfo = [], pathList = [], that = this;
            for(let i=0; i<files.length; i++){
                let info = files[i];
                // #ifdef APP-PLUS
                if(info.md5){
                    fn(info.md5)
                }else{
                    md5(info.path, fn)
                }
                // #endif
                // #ifdef H5
                md5(info, fn)
                // #endif
                function fn(str){
                    // #ifdef H5
                    type = info.name.split('.').pop()
                    // #endif
                    // #ifdef APP-PLUS
                    type = info.name?info.name.split('.').pop():info.path.split('.').pop()
                    // #endif
                    info.md5 = str
                    fileInfo.push({upType: type, md5: str})
                    if(files.length == fileInfo.length){
                        that.selectAllFlies = files
                        that.getUpload(fileInfo, files)
                    }
                }
            }
        },
        getUpload(fileInfo, files){
            // fileInfo,{upType: type, md5: str};files 上传获取的路径
            let fileInfoStr = JSON.stringify(fileInfo)
            let path = this.userId?'file/getUploadMsgFileParams':'file/getUploadFileParams'
            let params = {fileInfo: fileInfoStr}
            // 聊天页面参数
            if(this.userId){
                params.id = this.userId
                params.type = this.userType
            }
            this.api.get(path, params).then(res=>{
                if(res.data.state != 'ok') return;
                let list = res.data.needUpload || [];
                let notNeedUpload = res.data.notNeedUpload || {};
                let notUploadValList = Object.values(notNeedUpload),
                    notUploadKeyList = Object.keys(notNeedUpload)
                this.confirmImages = [];
                this.notConfirmImages = []
                
            // console.log(259, res)
                // 已上传过了，不需要再重新上传的图片
                if(notUploadValList.length>0){
                    for (const key in notNeedUpload) {
                        let index = fileInfo.findIndex(item => item.md5 == key);
                        let delData = files[index]
                       
                        // 传文件时，加上size
                        if(this.sendMsgType==8){
                            this.notConfirmImages.push({path: notNeedUpload[key], size: delData.size, name: delData.name});
                        }else{
                            this.notConfirmImages.push(notNeedUpload[key])
                        }

                        fileInfo.splice(index, 1)
                    }
                }
                if(list==0 && this.notConfirmImages.length>0){
                    let sendFiles = []
                    for(let i=0; i<this.notConfirmImages.length; i++){
                        let path = this.notConfirmImages[i];
                        if(this.sendMsgType==8){
                            path = this.notConfirmImages[i].path
                        }
                        sendFiles.push({type: path.split('.').pop(), path: path, msgType: this.sendMsgType, name: this.sendMsgType==8?this.notConfirmImages[i].name:'', size: this.notConfirmImages[i].size})
                    }
                    this.$emit('chooseFile', this.sendMsgType, this.selectAllFlies, sendFiles)
                    return
                }
                // 需要上传的图片
                for(let i=0; i<list.length; i++){
                    this.confirmImages.push({type: fileInfo[i].upType, key: list[i].key, md5: fileInfo[i].md5})
                    let filesInfo = files.find(info=>list[i].md5 == info.md5)
                    // 传文件时，加上size
                    if(this.sendMsgType==8){
                        this.sendImages.push({path: list[i].key, size: filesInfo.size, name: filesInfo.name});
                    }
                    // else if(this.sendMsgType==3){
                    //     console.log(303, this.sendMsgType)
                    //     this.sendImages.push(list[i].key);
                    // }
                    this.uploadFile(filesInfo.path, list[i], files.length)
                }
            })
        },
        chooseVideo(){
            this.sendImages = [];
            let that = this
            this.sendMsgType = 3
            uni.chooseVideo({
                sourceType: ['album', 'camera'],// 'camera', 
                success: function (res) {
                    // #ifdef H5
                    let info = res.tempFile
                    // #endif
                    // #ifdef APP-PLUS
                    let info = res
                    // #endif
                    
                    // console.log(info, res, res.tempFilePath)
                    if(info.size > that.size*1024*1024){
                        that.utils.showToast(`视频不能查过${that.size}M`)
                        return
                    }
                    // console.log(337, this.sendImages, info)
                    // return
                    // #ifdef H5
                    let type = info.name.split('.').pop()
                    md5(info, fn)
                    // #endif
                    // #ifdef APP-PLUS
                    let type = info.tempFilePath.split('.').pop()
                    md5(info.tempFilePath, fn)
                    // #endif
                    function fn(str){
                        let fileInfo = [{upType: type, md5: str}]
                        // return
                        that.selectAllFlies = [{path: res.tempFilePath, md5: str}]
                        that.getUpload(fileInfo, that.selectAllFlies)
                    }
                }
            })
        },
        chooseImage(){
            this.sendImages = [];
            this.sendMsgType = 1
            uni.chooseImage({
                count: 9, 
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], //从相册选择
                success: (res) => {
                    let list = res.tempFiles, type='', that = this;
                    
                    // console.log(360, list)
                    this.chooseFileChange(list)
                    // let data = []
                   
                    
                }
            })
        },
    }
}
function md5 (file, fun){
    // #ifdef APP-PLUS
    uni.getFileInfo({
        filePath: file,
        digestAlgorithm: 'md5',
        success: (res)=>{
            fun(res.digest)
        }
    })
    // #endif
    // #ifdef H5
	var spark = new SparkMD5.ArrayBuffer()
   	//获取文件二进制数据
  	var fileReader = new FileReader()
   	fileReader.readAsArrayBuffer(file) //file就是获取到的文件
   	//异步执行函数
   	fileReader.onload = function (e) {
		spark.append(e.target.result)
		let str = spark.end()
		
		//打印结果这个文件会有一串唯一编码类似下面
		//4b4a94c7ff8953d7103515e91d432b0a
		fun(str)
   }
    // #endif
}
</script>
<style lang="less" scoped>
    .upload-file{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 320rpx;
		height: 80rpx;
		border-radius: 20rpx;
		border: 1rpx solid #BFBFBF;
		font-size: 32rpx;
		image{
			width: 28rpx;
			margin-right: 20rpx;
		}
	}
</style>